<template>
  <div class="navigation-page">
    <div class="navbar">
      <a @click="goBack" class="navbar-back">
        <i class="fas fa-arrow-left"></i>
      </a>
      <div class="navbar-title">导航</div>
      <div style="width: 24px;"></div>
    </div>
    <div id="map-container" class="map-container"></div>
    <div v-if="loading" class="loading-overlay">
      <i class="fas fa-spinner fa-spin"></i>
      <span>正在规划路线...</span>
    </div>
    <div v-if="error" class="error-overlay">
      <span>{{ error }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showToast } from 'vant';

declare const AMap: any;

interface Destination {
  longitude: number;
  latitude: number;
  name: string;
}

const route = useRoute();
const router = useRouter();
const destination = ref<Destination | null>(null);
const loading = ref(true);
const error = ref<string | null>(null);
let map: any = null;

const goBack = () => router.back();

onMounted(() => {
  const { longitude, latitude, storeName } = route.query;
  if (!longitude || !latitude) {
    error.value = "无效的目标地址";
    loading.value = false;
    showToast('无效的目标地址');
    return;
  }
  destination.value = {
    longitude: parseFloat(longitude as string),
    latitude: parseFloat(latitude as string),
    name: storeName as string
  };

  const geolocation = new AMap.Geolocation({
    enableHighAccuracy: true,
    timeout: 10000,
  });

  geolocation.getCurrentPosition((status: string, result: any) => {
    if (status === 'complete' && result.position) {
      const startPoint = [result.position.lng, result.position.lat];
      if (destination.value) {
        const endPoint = [destination.value.longitude, destination.value.latitude];
        initMapAndRoute(startPoint, endPoint);
      }
    } else {
      error.value = "定位失败: " + result.message;
      loading.value = false;
      showToast('定位失败: ' + result.message);
    }
  });
});

const initMapAndRoute = async (startPoint: number[], endPoint: number[]) => {
  try {
    map = new AMap.Map('map-container', {
      zoom: 12,
      center: startPoint
    });

    // 添加起点标记
    new AMap.Marker({
      position: new AMap.LngLat(startPoint[0], startPoint[1]),
      offset: new AMap.Pixel(-13, -30),
      content: '<div class="marker-start">起</div>',
      map: map
    });

    // 添加终点标记
    new AMap.Marker({
      position: new AMap.LngLat(endPoint[0], endPoint[1]),
      offset: new AMap.Pixel(-13, -30),
      content: '<div class="marker-end">终</div>',
      map: map
    });

    const key = '6753f35feab64d68da6a1e51fa2054f6';
    const origin = startPoint.join(',');
    const destination = endPoint.join(',');
    const url = `https://restapi.amap.com/v5/direction/driving?origin=${origin}&destination=${destination}&key=${key}&show_fields=polyline`;
    
    const response = await fetch(url);
    const data = await response.json();

    loading.value = false;

    if (data.status === '1' && data.route && data.route.paths && data.route.paths.length > 0) {
      const path = data.route.paths[0];
      if (path.steps && path.steps.length > 0) {
        
        const polylines = path.steps
          .map((step: any) => step.polyline)
          .filter((p: any) => p && typeof p === 'string');

        if (polylines.length > 0) {
          const allPolylinesStr = polylines.join(';');
          const pathArray = allPolylinesStr.split(';')
            .filter((p: any) => p)
            .map((p: string) => {
              const parts = p.split(',');
              if (parts.length === 2) {
                return [parseFloat(parts[0]), parseFloat(parts[1])];
              }
              return [NaN, NaN];
            });

          const validPathArray = pathArray.filter((p: any) => !isNaN(p[0]) && !isNaN(p[1]));

          if (validPathArray.length > 0) {
            const polyline = new AMap.Polyline({
              path: validPathArray,
              strokeColor: "#3490dc",
              strokeOpacity: 0.8,
              strokeWeight: 6,
              strokeStyle: "solid",
            });

            map.add(polyline);
            map.setFitView();
          } else {
            error.value = '路线规划失败: 无法解析路线数据';
            showToast('路线规划失败: 无法解析路线数据');
          }
        } else {
          error.value = '路线规划失败: 路线不含坐标数据';
          showToast('路线规划失败: 路线不含坐标数据');
        }
      } else {
        error.value = '路线规划失败: 未返回路线分段数据';
        showToast('路线规划失败: 未返回路线分段数据');
      }
    } else {
      error.value = '路线规划失败: ' + data.info;
      showToast('路线规划失败: ' + data.info);
    }

  } catch(e) {
    loading.value = false;
    error.value = "地图加载或路线规划失败";
    showToast("地图加载或路线规划失败");
    console.error(e);
  }
};

</script>

<style scoped>
.navigation-page {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 50;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: white;
  border-bottom: 1px solid #e2e8f0;
}

.navbar-back {
  cursor: pointer;
}

.navbar-title {
  font-size: 18px;
  font-weight: 500;
}

.map-container {
  flex-grow: 1;
  margin-top: 57px;
}

.loading-overlay,
.error-overlay {
  position: absolute;
  top: 57px;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  color: #333;
  flex-direction: column;
}

.loading-overlay i {
  font-size: 24px;
  margin-bottom: 10px;
}

:global(.marker-start),
:global(.marker-end) {
  position: relative;
  color: white;
  border-radius: 5px;
  padding: 4px 8px;
  font-size: 12px;
  white-space: nowrap;
  border: 1px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

:global(.marker-start) {
  background-color: #3490dc; /* Blue for start */
}

:global(.marker-end) {
  background-color: #e53e3e; /* Red for end */
}

:global(.marker-start::after),
:global(.marker-end::after) {
  content: '';
  position: absolute;
  bottom: -6px;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
}

:global(.marker-start::after) {
  border-top: 6px solid #3490dc;
}

:global(.marker-end::after) {
  border-top: 6px solid #e53e3e;
}
</style> 